/*
 * name: uploadimg.js
 * version: v0.3.2
 * update: cancel传进程id
 * date: 2015-12-03
 */
define('uploadimg', function(require, exports, module) {
	//var $ = require('jquery');
	var def = {
		url: appcfg.host.backend + "/wcm/common/resource/upload.do?sid="+appcfg.project.sid,
		onCreate:function(opCode){
			appcan.window.openToast('正在上传...', '1000', 5);
		},
		onCreateError:function(){
			appcan.window.openToast('创建上传失败', '2000', 5);
		},
		onStatus:function(percent){
			appcan.window.openToast('正在上传:'+percent+'%', '500', 5);
		},
		success:function(remoteUrl){

		},
		cancel:function(cancel){
			appcan.window.openToast('取消上传', '2000', 5);
		},
		error:function(){
			appcan.window.openToast('上传失败', '2000', 5);
		}
	};
	var uploadImg = function(localImgPath, option) {
		var opt = $.extend(def, option || {}),
			uploadHost = opt.url,
			randOpId = Math.floor(Math.random() * (1000 + 1));
		uexUploaderMgr.onStatus = function(opCode, fileSize, percent, serverPath, status) {
			switch (status) {
				case 0:
					opt.onStatus(percent);
					break;
				case 1:
					if (serverPath.split) {
						serverPath = JSON.parse(serverPath);
					}
					opt.timer && clearTimeout(opt.timer);
					opt.success(serverPath.fullPath);
					uexUploaderMgr.closeUploader(opCode);
					break;
				case 2:
					opt.timer && clearTimeout(opt.timer);
					opt.error();
					uexUploaderMgr.closeUploader(opCode);
					break;
			}
		}
		uexUploaderMgr.cbCreateUploader = function(opCode, dataType, data) {
			if (data == 0) {
				var userAgent = navigator.userAgent;
				var path = localImgPath;
				var quality = 1;
				var maxWidth = 800;
				//华为高端机型图片压缩bug
				if (/HUAWEI/.test(userAgent)) {
					quality = 0;
				}
				setTimeout(function(){
					uexUploaderMgr.uploadFile(opCode, path, "inputName", quality, maxWidth);
				},0);
				opt.timer = setTimeout(function(){
					$.box.confirm('上传超时，是否取消?',function(){
						$.box.hide();
						window.uexUploaderMgr && uexUploaderMgr.closeUploader(opCode);
						opt.cancel(opCode);
					},function(){

					},{
						bgclose:false,
						oktext:'取消',
						canceltext:'等待'
					})
				},appcfg.set.longtime);
				return opt.onCreate(opCode);
			} else {
				return opt.onCreateError();
			}
		}
		uexUploaderMgr.createUploader(randOpId, uploadHost);
	}

	module.exports = uploadImg;
});